This guide uses maps from my GitHub page produced using shapefiles from OSi and OSNI.
Three packages are used throughout, they are tidyverse, sf and leaflet. Tidyverse is actually a collection of packages that all work together. sf stands for simple features, it is a package for working with spatial data, and it is designed to be compatible with tidyverse. Leaflet is a package for making interactive plots.
library(tidyverse)
library(sf)
library(leaflet)
Here I am using the map of 166 local electoral areas (LEAs) that I also use for the guide to making maps of Ireland.
lea_166 <- st_read("https://raw.githubusercontent.com/brendanjodowd/maps/main/lea_166.geojson")
Interactive maps can be easily created using the leaflet package. Creating an interactive map using leaflet starts with an empty leaflet function. Then you can add shapes using addPolygons.
We will see how many of the options for adjusting the appearance of maps with ggplot have similar counterparts in leaflet. There are two differences you should know about at the outset. The first is that with leaflet you build up the map using the pipe %>% whereas with ggplot/geom_sf you add bits using plus +. The second difference is that ggplot accepts either the UK or US spellings of colour/color in its functions and arguments, but leaflet always uses the US version “color”.
leaflet() %>%
addPolygons(data = lea_166)
Let’s tailor the appearance of this map using additional arguments for addPolygons. We can specify the colour, line weight and opacity of lines using the arguments color, weight and opacity, and we can specify the fill colour and fill opacity using fillColor and fillOpacity. We can create a label based on variable that appears when we hover over a region using label = followed by ~ and the variable name.
Let’s use these features to create a map where LEAs in the West NUTS3 region are highlighted in green, and all other LEAs are transparent. We’ll do this by creating two layers as follows, with a label for LEA name on the topmost layer.
leaflet() %>%
addPolygons(data = lea_166 %>% filter(NUTS3 == "West"),
color="black", weight=1 , opacity=1, fillColor="green", fillOpacity=0.3) %>%
addPolygons(data=lea_166,
color="black", weight=1 , opacity=1, fillOpacity=0, label=~LEA)